package com.novel.system.controller;


import com.novel.common.constants.Constants;
import com.novel.framework.base.BaseController;
import com.novel.framework.factory.AsyncFactory;
import com.novel.framework.result.Result;
import com.novel.framework.shiro.TokenService;
import com.novel.framework.shiro.utils.ShiroUtils;
import com.novel.kaptcha.adapter.Kaptcha;
import com.novel.kaptcha.exception.KaptchaIncorrectException;
import com.novel.system.domain.LoginUser;
import com.novel.system.domain.SysUser;
import com.novel.system.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;

/**
 * 用户登录控制器
 *
 * @author novel
 * @date 2019/3/18
 */
@RestController
public class LoginController extends BaseController {
    @Resource
    private Kaptcha kaptcha;
    private final SysUserService userService;
    private final TokenService tokenService;
    private final AsyncFactory asyncFactory;

    public LoginController(SysUserService userService, TokenService tokenService, AsyncFactory asyncFactory) {
        this.userService = userService;
        this.tokenService = tokenService;
        this.asyncFactory = asyncFactory;
    }


    @PostMapping("/login")
    public Result login(@NotBlank(message = "用户名不能为空") String userName, @NotBlank(message = "密码不能为空") String password,
                        @NotBlank(message = "验证码key不能为空") String key, @NotBlank(message = "验证码不能为空") String code,
                        @RequestParam(name = "rememberMe", required = false, defaultValue = "false") boolean rememberMe, HttpServletResponse httpServletResponse) {
        if (!kaptcha.validate(key, code)) {
            throw new KaptchaIncorrectException("验证码不正确");
        }

        SysUser login = userService.login(userName, password);
        //比对密码
        if (login != null) {
            LoginUser loginUser = new LoginUser();
            loginUser.setUser(login);
            login.setRememberMe(rememberMe);
            String token = tokenService.createToken(loginUser);

            httpServletResponse.setHeader(Constants.AUTHORIZATION, token);
            httpServletResponse.setHeader("Access-Control-Expose-Headers", Constants.AUTHORIZATION);
            //记录登录信息
            asyncFactory.recordLogininfor(loginUser);
            //更新用户登录信息
            asyncFactory.updateLoginUser(loginUser);
            return success("登录成功！");
        } else {
            return error("登录失败！");
        }
    }

    @PostMapping("/logout")
    public Result logout() {
        tokenService.delLoginUser(ShiroUtils.getToken());
        SecurityUtils.getSubject().logout();
        return success("退出成功！");
    }

}
